# app.py
from flask import Flask, render_template, request, redirect, url_for
from flask_sqlalchemy import SQLAlchemy
from config import Config

app = Flask(__name__)
app.config.from_object(Config)

db = SQLAlchemy(app)

# DCO 模型
class DCO(db.Model):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(100), nullable=False)
    email = db.Column(db.String(100), nullable=False)
    signed = db.Column(db.Boolean, default=False)

    def __repr__(self):
        return f'<DCO {self.name}>'

# 首页，展示 DCO 信息列表
@app.route('/')
def index():
    dcos = DCO.query.all()
    return render_template('index.html', dcos=dcos)

# 添加新 DCO 信息
@app.route('/add', methods=['POST'])
def add_dco():
    name = request.form.get('name')
    email = request.form.get('email')
    signed = request.form.get('signed') == 'on'

    new_dco = DCO(name=name, email=email, signed=signed)
    db.session.add(new_dco)
    db.session.commit()

    return redirect(url_for('index'))

# 更新 DCO 信息
@app.route('/update/<int:id>', methods=['GET', 'POST'])
def update_dco(id):
    dco = DCO.query.get_or_404(id)

    if request.method == 'POST':
        dco.name = request.form.get('name')
        dco.email = request.form.get('email')
        dco.signed = request.form.get('signed') == 'on'

        db.session.commit()
        return redirect(url_for('index'))

    return render_template('update.html', dco=dco)

# 删除 DCO 信息
@app.route('/delete/<int:id>', methods=['GET'])
def delete_dco(id):
    dco = DCO.query.get_or_404(id)
    db.session.delete(dco)
    db.session.commit()

    return redirect(url_for('index'))

# 启动数据库
@app.before_first_request
def init_db():
    db.create_all()

if __name__ == '__main__':
    app.run(debug=True)
